package com.sky.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sky.entity.User;
import com.sky.entity.Userc;
import com.sky.service.UserService;
import com.sky.service.UsercService;
import com.sky.service.WXservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class WXserviceImpl implements WXservice {
    @Autowired
    private UserService userService;

    @Autowired
    private WxMaService wxMaService;

    @Override
    public User login(String code) {
        try {
            //获取OpenId
            WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
            String openid = sessionInfo.getOpenid();

            //查询是否存在该用户
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getOpenid, openid);
            User user = userService.getOne(wrapper);

            if (user == null) {
                //不存在则创建新用户
                user = new User();
                user.setName(String.valueOf(System.currentTimeMillis()));//使用当前时间戳作为临时用户名
                user.setAvatar("https://www.baidu.com");//默认头像URL
                user.setOpenid(openid);
                userService.save(user);
            }

            //返回用户信息
            return user;
        } catch (Exception e) {
            throw new RuntimeException("微信登录失败", e);
        }
    }

}
